package com.pocketsweet.ui.fragments;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;

import com.avos.avoscloud.AVAnalytics;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.pocketsweet.R;
import com.pocketsweet.MLApplication;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLTopic;
import com.pocketsweet.ui.Main;
import com.pocketsweet.ui.Topic;
import com.pocketsweet.ui.TopicActivity;
import com.pocketsweet.ui.TopicArticle;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.MyPagerGalleryView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.MyPagerGalleryView.MyOnItemClickListener;
import com.pocketsweet.ui.uilib.adapter.RecommendArticleListAdapter;
import com.pocketsweet.ui.uilib.adapter.RecommendArticleListAdapter.ViewHolder_article;
import com.pocketsweet.utils.ToolKits;

public class RecommendFragment extends Fragment implements OnRefreshListener,
        OnLoadListener, OnItemClickListener {
    private Context mContext;
    private ArrayList<String> ImageList = new ArrayList<String>();// banner图片

    private MyPagerGalleryView gallery;
    private LinearLayout ovalLayout;
    public static AutoListView articleListview = null;
    public static List<MLArticle> articlesList = new ArrayList<MLArticle>();
    public static List<MLTopic> mlTopicList = new ArrayList<MLTopic>();
    private static RecommendArticleListAdapter recommendArticleListAdapter;
    public static final int MORE_DATA_MAX_COUNT = 10; // 每页5个对象
    private boolean IS_UPDATE_LIST = false; // 是否刷新列表
    public int skipDataCount = 0; // 忽略前N个对象
    public static final int BEGIN_TO_LOADING = -1;// 刚进入时列表为空的状态
    private MLApplication mlApplication;
    public MyPagerGalleryView gallery_ad;
    private View viewGallery;
    public static MLArticle mlArticle;
    private LinearLayout linBlank;
    public static boolean isCommentRefresh = false;
    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(Main.ACTION_LIKE_RECOMMEND_REFRESH)) {
                recommendArticleListAdapter.notifyDataSetChanged();
            }
        }
    };

    public ViewHolder_article articleHolder;

    public static int oldStart = -1;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_recommend, null);
        viewGallery = inflater.inflate(R.layout.item_recommend_advertise, null);
        ViewUtils.inject(this, rootView);
        mlApplication = (MLApplication) getActivity().getApplication()
                .getApplicationContext();
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mContext = getActivity();
        // 当推荐的列表为空，也就是第一次的时候才加载
        initRecommendList(BEGIN_TO_LOADING);

    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Main.ACTION_LIKE_RECOMMEND_REFRESH);
        getActivity().registerReceiver(receiver, filter);

    }

    @Override
    public void onResume() {
        super.onResume();
        if (articleHolder != null) {
            articleHolder.update(mlArticle);
            articleHolder = null;
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        getActivity().unregisterReceiver(receiver);
    }

    @Override
    public void onAttach(Activity activity) {
        // ToolKits.toast(getActivity(), "attch");
        super.onAttach(activity);
    }

    /*
     * 初始化列表
     */
    private void initRecommendList(int what) {
        articleListview = (AutoListView) getActivity().findViewById(
                R.id.articleListview);
        linBlank = (LinearLayout) getView().findViewById(R.id.linBlank);

        // gallery = (MyPagerGalleryView) viewGallery
        // .findViewById(R.id.adgallery);
        recommendArticleListAdapter = new RecommendArticleListAdapter(
                getActivity(), articlesList);
        articleListview.setAdapter(recommendArticleListAdapter);
        articleListview.setPageSize(MORE_DATA_MAX_COUNT);
        articleListview.setOnRefreshListener(this);
        articleListview.setOnLoadListener(this);
        articleListview.setOnItemClickListener(this);
        // gallery.setMyOnItemClickListener(this);
        getRecommendList(what);
    }

    public static List<MLTopic> getMlTopicList() {
        recommendArticleListAdapter.notifyDataSetChanged();

        return mlTopicList;
    }

    public static void setMlTopicList(List<MLTopic> mlTopicList) {
        RecommendFragment.mlTopicList = mlTopicList;
    }

    /*
     * 加载列表
     */
    private void getRecommendList(final int what) {
        if (what != BEGIN_TO_LOADING) {
            IS_UPDATE_LIST = true; // 如果不是首次加载数据，则该动作为刷新
        }
        articlesList = mlApplication.getmArticle(); // 从MLContext里获取articlesList，若为空则获取网络数据
        if (articlesList == null || articlesList.size() <= 0 || IS_UPDATE_LIST) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud
            AVQuery<MLArticle> query = new AVQuery<MLArticle>("MLArticle");
            final AVQuery<MLTopic> queryTopic = new AVQuery<MLTopic>("MLTopic");
            skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
            if (what != AutoListView.LOAD) {
                skipDataCount = 0; // 刷新时不用忽略前面对象
                AVAnalytics.onEvent(getActivity(), "梦想恋人页面刷新");
            }
            query.setSkip(skipDataCount); // 忽略前N个
            query.orderByDescending("publishTime"); // 按照文章发表时间排序
            query.limit(MORE_DATA_MAX_COUNT); // 设置每页对象个数
            query.whereEqualTo("status", 1); // 状态为发布
            // query.include("objectId");
            query.findInBackground(new FindCallback<MLArticle>() {
                @Override
                public void done(final List<MLArticle> article, AVException e) {
                    // loading.dismiss();
                    // 取出参与的人
                    // Log.e("==user==", users.toString() + " ");
                    if (e == null && article.size() != 0) {
                        queryTopic.orderByDescending("priority"); // 按照优先级排序
                        queryTopic.whereEqualTo("status", 1); // 状态为发布
                        queryTopic
                                .findInBackground(new FindCallback<MLTopic>() {
                                    public void done(List<MLTopic> mlTopic,
                                                     AVException e) {
                                        if (e == null) {
                                            // Log.e("getTopic成功",
                                            // "查询到" + mlTopic.size()
                                            // + " 条符合条件的数据");
                                            if (mlTopic.size() > 0) {
                                                setMlTopicList(mlTopic);
                                                switch (what) {
                                                    case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
                                                        articlesList = article;
                                                        articleListview
                                                                .onRefreshComplete();
                                                        Main.clearRecommendRecord();
                                                        break;
                                                    case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
                                                        articleListview
                                                                .onLoadComplete();
                                                        articlesList
                                                                .addAll(article);

                                                        break;
                                                    case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
                                                        articlesList = article;
                                                        articleListview
                                                                .onRefreshComplete();
                                                        break;
                                                }
                                                mlApplication
                                                        .setmArticle(articlesList);
                                                articleListview
                                                        .setResultSize(articlesList
                                                                .size());
                                                recommendArticleListAdapter.notifyDataSetChanged();

                                                if (skipDataCount == 0) {
                                                    for (int i = 0; i < articlesList
                                                            .size(); i++) {
                                                        if (1 == ToolKits
                                                                .isYeaterday(
                                                                        articlesList
                                                                                .get(i)
                                                                                .getPublishTime(),
                                                                        null)) {
                                                            recommendArticleListAdapter = new RecommendArticleListAdapter(
                                                                    getActivity(),
                                                                    articlesList,
                                                                    i);
                                                            oldStart = i;
                                                            articleListview
                                                                    .setAdapter(recommendArticleListAdapter);
                                                            recommendArticleListAdapter.notifyDataSetChanged();
                                                            break;
                                                        }
                                                    }

                                                }
                                                linBlank.setVisibility(View.GONE);
                                                //
                                                // articleListview
                                                // .setSelection(skipDataCount);
                                                // recommendArticleListAdapter
                                                // .setDatas(advertiseList);
                                                // recommendArticleListAdapter
                                                // .notifyDataSetChanged();

                                                IS_UPDATE_LIST = false; // 刷新完毕，设为false
                                            }
                                        } else {
                                            // Log.e("getTopic失败",
                                            // "查询错误: " + e.getMessage());
                                            getRecommendList(BEGIN_TO_LOADING); // 重新加载
                                            linBlank.setVisibility(View.VISIBLE);
                                        }
                                    }
                                });
                    } else {
                        // 已加载完全部，取消loading
                        articleListview.setNoData();
                    }
                }
            });
        } else {
            recommendArticleListAdapter.oldCount = oldStart;
        }

    }

    // @Override
    // public void onPause() {
    // gallery.stopTimer();
    // super.onPause();
    // }
    //
    // @Override
    // public void onResume() {
    // Log.v("molian", "----------我恢复了");
    // gallery.startTimer();
    // super.onResume();
    // }

    @Override
    public void onLoad() {
        getRecommendList(AutoListView.LOAD);

    }

    @Override
    public void onRefresh() {
        IS_UPDATE_LIST = true;
        initRecommendList(AutoListView.REFRESH);
        // getRecommendList(AutoListView.REFRESH);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
        if (position - 1 < 0 || recommendArticleListAdapter.getCount() <= 0 || position - 1 >= recommendArticleListAdapter.getCount()) {
            return;
        }
        Intent intent = new Intent(getActivity(), TopicArticle.class);
        mlArticle = articlesList.get(position - 1);
        articleHolder = recommendArticleListAdapter.new ViewHolder_article(view);
        intent.putExtra("articleId", mlArticle.getObjectId());
        intent.putExtra("position", String.valueOf(position - 1));
        getActivity().startActivity(intent);

    }

}
